// 将$data中的成员转化为getter和setter
class Observer {
    constructor(data) {
        this.walk(data);
    }
    walk(data) {
        if (!data || typeof data !== "object") return;
        Object.keys(data).forEach(key => {
            this.defineReactive(data, key, data[key]);
        });
    }
    defineReactive(data, key, val) {
        const self = this;
        // 收集依赖
        let dep = new Dep();
        this.walk(val);
        Object.defineProperty(data, key, {
            enumerable: true,
            configurable: true,
            get() {
                Dep.target && dep.addSub(Dep.target)
                return val; // 不能直接调用data[key]，会产生死递归
            },
            set(newVal) {
                if (val == newVal) return;
                val = newVal;
                self.walk(newVal);

                dep.notify()
            },
        });
    }
}
